import Toast from 'tdesign-miniprogram/toast/index';
import Log from '../../utils/log';
import commondUtil from '../../utils/commondUtil';
import Login from '../../api/modules/login';

Page({
  data: {
    showOriginalPwdFlag: false,

    username: '',
    password: '',
    loginBtnLoading: false,
  },

  onLoad(options) {
    if (commondUtil.isNotBlank(wx.getStorageSync('token'))) {
      wx.switchTab({
        url: '/pages/signClient/signClient'
      });
    }
    const lastLoginUsername = wx.getStorageSync('lastLoginUsername');
    if (commondUtil.isNotBlank(lastLoginUsername)) {
      this.setData({
        username: lastLoginUsername
      });
    }
  },
  loginHandle() {
    const user = {
      username: this.data.username,
      password: this.data.password,
    }
    if (commondUtil.isBlank(user.username) || commondUtil.isBlank(user.password)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '用户名或密码不可为空',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    if (user.password.length < 6) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '密码不得少于6位数',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    this.setData({
      loginBtnLoading: true
    });
    Login.login(user).then(resp => {
      const userInfo = resp?.data;
      if (commondUtil.isEmpty(userInfo)) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: resp?.message ? resp.message : '登录失败！',
          theme: 'error',
          direction: 'column',
        });
        return;
      }
      // 存储token和用户信息
      wx.setStorageSync('token', userInfo.accessToken);
      wx.setStorageSync('refreshToken', userInfo.refreshToken);
      wx.setStorageSync('userInfo', userInfo);
      wx.setStorageSync('lastLoginUsername', user.username);
      if (getCurrentPages().length > 1) {
        // 回到上一页
        wx.navigateBack();
        return;
      }

      // 跳转到客户端页面
      wx.switchTab({
        url: '/pages/signClient/signClient'
      });
    }).catch(e => {
      Log.errorAll("登录失败", e);
      Toast({
        context: this,
        selector: '#t-toast',
        message: e?.message ? e.message : '登录失败！',
        theme: 'error',
        direction: 'column',
      });
    }).finally(() => {
      this.setData({
        loginBtnLoading: false
      });
    });
  },

  showOriginalPwd() {
    this.setData({
      showOriginalPwdFlag: !this.data.showOriginalPwdFlag
    });
  },

})